<?php
require_once 'config.php';

function getDbConnection() {
    $conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
    if ($conn->connect_error) {
        die("连接失败: " . $conn->connect_error);
    }
    $conn->set_charset("utf8mb4");
    return $conn;
}

function generateSignature($params, $secret) {
    // 1. 参数排序
    ksort($params);
    
    // 2. 构建签名字符串
    $stringToBeSigned = '';
    foreach ($params as $key => $value) {
        if ($value !== '' && !is_null($value) && $key != '_aop_signature') {
            // 确保值是字符串类型
            $value = is_array($value) ? json_encode($value) : (string)$value;
            
            if ($stringToBeSigned !== '') {
                $stringToBeSigned .= '&';
            }
            // 不进行URL编码，保持原始值
            $stringToBeSigned .= $key . '=' . $value;
        }
    }
    
    // 调试输出
    echo "String to sign: " . $stringToBeSigned . "\n";
    
    // 3. 生成签名
    return strtoupper(md5($secret . $stringToBeSigned));
}

function callAlibabaApi($method, $params = []) {
    // API版本和命名空间
    $namespace = 'com.alibaba.product';
    $version = '1';
    
    // 构建API URL
    $baseUrl = 'https://gw.open.1688.com/openapi/param2';
    $apiUrl = sprintf('%s/%s/%s/%s/%s', $baseUrl, $version, $namespace, $method, APP_KEY);
    
    // 添加公共参数
    $commonParams = [
        'app_key' => APP_KEY,
        'sign_method' => 'md5',
        'timestamp' => date('Y-m-d H:i:s'),
        'format' => 'json',
        'v' => '2.0',
        'session' => '' // 如果需要授权访问，这里填写授权码
    ];
    
    // 合并参数并确保所有值都是字符串类型
    $params = array_merge($commonParams, $params);
    foreach ($params as $key => &$value) {
        if (is_array($value)) {
            $value = json_encode($value, JSON_UNESCAPED_UNICODE);
        } else {
            $value = (string)$value;
        }
    }
    
    // 生成签名
    $params['sign'] = generateSignature($params, APP_SECRET);
    
    // 构建完整URL
    $url = $apiUrl;
    
    // 调试输出
    echo "Request URL: " . $url . "\n";
    echo "Request Params: " . json_encode($params, JSON_PRETTY_PRINT) . "\n";
    
    // 发起请求
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $url,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => http_build_query($params),
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_HEADER => false,
        CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
        CURLOPT_HTTPHEADER => [
            'Content-Type: application/x-www-form-urlencoded;charset=utf-8'
        ]
    ]);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    
    // 调试输出
    echo "Response Code: " . $httpCode . "\n";
    echo "Response Body: " . $response . "\n";
    
    if(curl_errno($ch)) {
        throw new Exception('Curl error: ' . curl_error($ch));
    }
    
    curl_close($ch);
    
    if($httpCode != 200) {
        throw new Exception('HTTP error: ' . $httpCode . ' Response: ' . $response);
    }
    
    return json_decode($response, true);
} 